﻿import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import { Bk_User } from './bk_user.entity';
import * as bcrypt from 'bcrypt';
@Injectable()
export class UsersService {
    constructor(
        @InjectRepository(Bk_User)
        private readonly usersRepository: Repository<Bk_User>
    ) { }

    async findAll(query: any): Promise<[Bk_User[], number]> {
        return await this.usersRepository.findAndCount({ where: { identity: "other" }, skip: query.skip, take: query.take });
    }

    async findOne(user_name: string): Promise<Bk_User> {
        return await this.usersRepository.findOne({ where: { user_name: user_name } });
    }

    async delete(id: number): Promise<DeleteResult> {
        return await this.usersRepository.delete(id);
    }

    async update(id: number, user: { user_name: string, user_password: string }): Promise<UpdateResult> {
        user.user_password = await bcrypt.hash(user.user_password, await bcrypt.genSalt(10));//加密
        return await this.usersRepository.update(id, user);
    }
    async updateUserinfo(userinfo: Bk_User) {
        return await this.usersRepository.update(userinfo.id, userinfo);
    }
    async add(user: { user_name: string, user_password: string }): Promise<void | any> {
        user.user_password = await bcrypt.hash(user.user_password, await bcrypt.genSalt(10));//加密
        try {//用户名唯一不重复
            return await this.usersRepository.save(user);
        } catch (error) {
            return {
                error_msg: '添加用户失败！',
                error_code: error.code
            };
        }
    }
    async create(union_id: string, userinfo?: any) {
        try {
            let nickname = '微信用户';
            let headimgurl = '';
            let phone = '';
            if (userinfo) {
                nickname = userinfo.nickname;
                headimgurl = userinfo.headimgurl;
                phone = userinfo.phone;
            }
            return await this.usersRepository.save({ union_id, nickname, headimgurl, phone });
        } catch (error) {
            return false;
        }
    }
    async findOneByUnionId(union_id: string) {
        try {
            return await this.usersRepository.findOne({ where: { union_id } });
        } catch (error) {
            return false;
        }
    }

}
